//
//  FirstTabBar.m
//  4-11-3-桌面抽屉效果
//
//  Created by Macbookpro on 15/4/11.
//  Copyright (c) 2015年 Macbookpro. All rights reserved.
//

#import "HomePageViewController.h"
#import "MyConnection.h"
#import "CycleScrollView.h"
#import "NSTimer+Addition.h"
#import "Singleton.h"
#import "VegetableMenu.h"
#import "UIImageView+WebCache.h"
#import "DetailController.h"
#import "CYLClassifyMenuViewController.h"
#import "MONActivityIndicatorView.h"

@interface HomePageViewController () <MONActivityIndicatorViewDelegate, UIAlertViewDelegate>

{
    CGAdapter _myAd;
    
    UIAlertView *_fileAlertView;
}

@property (nonatomic, retain) UIButton *backButton;
@property (nonatomic , retain) CycleScrollView *mainScorllView;
@property (nonatomic, retain) NSMutableArray *ViewArray;
@property (nonatomic, retain) UIPageControl *page;
@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UILabel *eLabel;
@property (nonatomic, retain) NSMutableArray *LabelArray;
@property (nonatomic, retain) NSMutableArray *eLableArray;
@property (nonatomic, retain) VegetableMenu *model;
@property (nonatomic, retain) NSMutableArray *allArray;

@property (nonatomic, retain) UIView *frontView;
@property (nonatomic, retain) NSTimer *netTimer;

@end

@implementation HomePageViewController



- (void)dealloc
{
    [_allArray release];
    [_mainScorllView release];
    [_ViewArray release];
    [_page release];
    [_label release];
    [_eLabel release];
    [_LabelArray release];
    [_eLableArray release];
    [_model release];
    [_backButton release];
    [_frontView release];
    [_netTimer release];
  
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.ViewArray = [NSMutableArray array];
        self.LabelArray = [NSMutableArray array];
        self.eLableArray = [NSMutableArray array];
        self.allArray = [NSMutableArray array];
        
        _myAd = [AdapterModel getCGAdapter];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
     [self createInvidate];
    [self.view setBackgroundColor:[UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0]];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self creatScrollView];
    [self creatButton];
    
   
}

#pragma mark - 创建小菊花
- (void)createInvidate
{
    self.frontView = [[UIView alloc] initWithFrame:self.view.frame];
    _frontView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5f];
    [self.view addSubview:_frontView];
    [_frontView release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notification) name:@"frontView3" object:nil];
    
    MONActivityIndicatorView *indicator = [[MONActivityIndicatorView alloc] init];
    indicator.delegate = self;
    indicator.numberOfCircles = 3;
    indicator.radius = 20;
    indicator.internalSpacing = 3;
    indicator.center = _frontView.center;
    
    // 隐藏顶部navigationbar
    self.navigationController.navigationBar.hidden = YES;
    
    [indicator startAnimating];
    [_frontView addSubview:indicator];
    [indicator release];
    
    self.netTimer = [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(isHaveFront) userInfo:nil repeats:NO];
}


// 加载成功
- (void)notification
{
    [_netTimer invalidate];
    self.navigationController.navigationBar.hidden = NO;
    [self.frontView removeFromSuperview];
    self.frontView = nil;
    
}

// 判断加载情况
- (void)isHaveFront
{
    if (_frontView != nil) {
        _fileAlertView = [[UIAlertView alloc] initWithTitle:@"加载失败" message:@"是否重新加载" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [_fileAlertView show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [_netTimer invalidate];
    }
    if (buttonIndex == 1) {
    
        [self creatScrollView];
    }
}




- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     self.navigationController.navigationBar.hidden = YES;
}

#pragma mark - 创建滚动图片的scrollview
- (void)creatScrollView
{
    __block HomePageViewController *my = self;
    __block NSTimer *myTimer = _netTimer;
    //接收数据
    
    NSMutableDictionary *dicP = [NSMutableDictionary dictionary];
    [dicP setObject:@"2" forKey:@"phonetype"];
    [dicP setObject:@"1" forKey:@"page"];
    [dicP setObject:@"6" forKey:@"pageRecord"];
    [dicP setObject:@"0" forKey:@"is_traditional"];
    [dicP setObject:@"" forKey:@"user_id"];
    
    [MyConnection connectWithUrl:HOMEPAGEURL parmaters:dicP finishBlock:^(NSData *data) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        [myTimer invalidate];
        
        NSMutableArray *array = [dic objectForKey:@"data"];
        
        //创建labelƒ
        my.label = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, my.view.frame.size.width - 50, 20)];
        _label.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:20];
        _label.textColor = [UIColor whiteColor];
        _label.shadowColor = [UIColor blackColor];
        _label.shadowOffset = CGSizeMake(1, -3);
        my.eLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 130, my.view.frame.size.width, 20)];
        _eLabel.font = [UIFont fontWithName:@"AmericanTypewriter-Bold" size:15];
        _eLabel.textColor = [UIColor whiteColor];
        _eLabel.shadowColor = [UIColor blackColor];
        _eLabel.shadowOffset = CGSizeMake(3, -3);
        
        for (int i = 0; i < array.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, my.view.frame.size.width, my.view.frame.size.height)];
            NSDictionary *dic = [NSDictionary dictionary];
            dic = [array objectAtIndex:i];
            my.model = [VegetableMenu vegetableMenuWithVegetable_id:[dic objectForKey:@"vegetable_id"] name:[dic objectForKey:@"name"] fittingRestriction:[dic objectForKey:@"fittingRestriction"] englishName:[dic objectForKey:@"englishName"] imagePathLandscape:[dic objectForKey:@"imagePathLandscape"] clickCount:[dic objectForKey:@"clickCount"] materialVideoPath:[dic objectForKey:@"materialVideoPath"] productionProcessPath:[dic objectForKey:@"productionProcessPath"]];
            
            [my.allArray addObject:my.model];
            
            NSURL *photoUrl = [NSURL URLWithString:_model.imagePathLandscape];
            
            NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            
            [imageView sd_setImageWithURL:photoUrl placeholderImage:image];
            
            [my.ViewArray addObject:imageView];
            [imageView release];
            
            _label.text = _model.name;
            [my.LabelArray addObject:_label.text];
            
            _eLabel.text = _model.englishName;
            [my.eLableArray addObject:_eLabel.text];
        }
        Singleton *single = [Singleton shareInterface];
        single.state = my.ViewArray.count - 1;
        //创建scrollView，x秒滚动一次
        my.mainScorllView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, my.view.frame.size.width, my.view.frame.size.height - 49) animationDuration:5];
        
        my.mainScorllView.num = _ViewArray.count;
        
        //创建pageControl
        my.page = [[UIPageControl alloc] initWithFrame:CGRectMake(0, _mainScorllView.frame.origin.y + _mainScorllView.frame.size.height - 50, self.view.frame.size.width, 30)];
        [_page setNumberOfPages:my.ViewArray.count];
        //获取第pageIndex个位置的contentView
        my.mainScorllView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
            
            if (pageIndex == single.state) {
                _label.text = my.LabelArray[single.state];
                _eLabel.text = my.eLableArray[single.state];
                _page.currentPage = single.state;
                
                return  _ViewArray[0];
            } else {
                _label.text = my.LabelArray[pageIndex];
                _eLabel.text = my.eLableArray[pageIndex];
                _page.currentPage = pageIndex;
                return _ViewArray[pageIndex + 1];
            }
            
        };
        //图片个数
        my.mainScorllView.totalPagesCount = ^NSInteger(void){
            return my.ViewArray.count;
        };
        //当点击的时候，执行的block
        my.mainScorllView.TapActionBlock = ^(NSInteger pageIndex){
            [my imageClick:pageIndex];
//            NSLog(@"点击了第%ld个",pageIndex);
        };
        
        //添加到self.view
        [my.view addSubview:my.mainScorllView];
        [_mainScorllView release];
       
        UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, my.view.frame.size.width, 64)];
        bar.backgroundColor = [UIColor colorWithRed:236/255.0 green:236/255.0 blue:236/255.0 alpha:1.0];
        [my.view addSubview:bar];
        [bar release];
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 40, 40)];
        [bar addSubview:button];
        [button release];
        [button setTitle:@"分类" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
       
        UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 50, 20, 40, 40)];
        [bar addSubview:button1];
        [button1 release];
        [button1 setTitle:@"搜索" forState:UIControlStateNormal];
        [button1 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button1 addTarget:my action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];
        [my.view addSubview:_page];
        [my.view addSubview:_label];
        [my.view addSubview:_eLabel];
        
        [_page release];
        [_label release];
        [_eLabel release];
    }];
}


#pragma mark - 点击首页图片响应事件
- (void)imageClick:(NSInteger)num
{
    if (num == [self.allArray count] - 1) {
        num = 0;
    }
    else {
        num += 1;
    }
    
    DetailController *detail = [[DetailController alloc] init];
    VegetableMenu *model = [self.allArray objectAtIndex:num];
    detail.vegetableMenuModel = model;
    self.navigationController.navigationBar.hidden = NO;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
}

- (void)creatButton
{

    UIButton *aButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 40, 40)];
    [aButton setTitle:@"分类" forState:UIControlStateNormal];
    
    [aButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [aButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:aButton] autorelease];
    
    [aButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [aButton release];
    
    UIButton *bButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 40, 40)];
    [bButton setTitle:@"搜索" forState:UIControlStateNormal];
    [bButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [bButton setTitleColor:[UIColor blueColor] forState:UIControlStateHighlighted];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:bButton] autorelease];
    [bButton addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];
    [bButton release];


}

- (void)button1Action:(id)sender
{
    CYLClassifyMenuViewController *controller = [[CYLClassifyMenuViewController alloc] init];
//push进去之后隐藏TabBar
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
    
}

- (void)buttonAction:(id)sender
{
    
    if (self.tabBarController.view.frame.origin.x == 0) {
        
        self.view.userInteractionEnabled = NO;
        
        [UIView animateWithDuration:0.5 animations:^{
            [self.tabBarController.view setFrame:CGRectMake(300 * _myAd.sWidth, 110 * _myAd.sHeight, self.view.frame.size.width - 100 * _myAd.sWidth, self.view.frame.size.height - 220 * _myAd.sHeight)];
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
        }];
//   设置返回Button
        _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        [_backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.tabBarController.view addSubview:_backButton];
        [_backButton release];
    }
    

}


- (void)backButtonAction:(id)sender
{
    self.view.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:0.5 animations:^{
        [self.tabBarController.view setFrame:CGRectMake(0, 0, self.view.frame.size.width + 100 * _myAd.sWidth, self.view.frame.size.height + 220 * _myAd.sHeight)];
    } completion:^(BOOL finished) {
       
        if (self.tabBarController.view.frame.origin.x == 0) {
            [_backButton removeFromSuperview];
        }
        self.view.userInteractionEnabled = YES;
    }];
    

}


@end
